<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC02
 * Date: 10/10/13
 * Time: 2:30 PM
 * To change this template use File | Settings | File Templates.
 */

class ForgotPasswordForm extends CFormModel {
    public $email;

    public function rules() {
        return array(
            array('email', 'required'),
            array('email', 'length', 'max'=>60),
            array('email', 'email'),
            array('email', 'existUser')
        );
    }

    public function existUser() {
        $user = User::model()->getByEmail($this->email);
        if (!$user) $this->addError('email', 'Your {attribute} does not exist');
    }

    public function forgot() {
        $user = User::model()->getByEmail($this->email);
        $user->reset_password = TreTodayCommon::unique_id(32);
        $user->save();

        //get email template
        $emailTemplate = EmailTemplate::model()->findByAttributes(array('type' => EmailTemplateType::ResetPassword));
        $search = array('{first_name}', '{last_name}', '{active_email_link}');
        $replace = array($user->first_name, $user->last_name, TreTodayUrl::resetPassword($user->reset_password));
        $content = str_replace($search, $replace, $emailTemplate->content);
        //add email to queue
        $mail = new EmailQueue();
        $mail->receiver = $this->email;
        $mail->subject = 'Reset Password';
        $mail->content = $content;
        $mail->time = time();
        $mail->status = EmailQueueStatus::Queuing;
        $mail->save();

        return $user->reset_password;
    }

}